package com.open.capacity.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;

import com.open.capacity.model.system.LoginAppUser;

import javax.annotation.Resource;
import java.util.LinkedHashMap;

/**
 * @author 作者 ftquan E-mail: 464725602@qq.com
 * @version 创建时间：2017年11月12日 上午22:57:51 获取用户信息
 */
public class SysUserUtil {

    /**
     * 获取登陆的 LoginAppUser
     *
     * @return
     */
    @SneakyThrows
    @SuppressWarnings("rawtypes")
    public static LoginAppUser getLoginAppUser() {

        ObjectMapper objectMapper = new ObjectMapper();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof OAuth2Authentication) {
            OAuth2Authentication oAuth2Auth = (OAuth2Authentication) authentication;
            authentication = oAuth2Auth.getUserAuthentication();

            if (authentication instanceof UsernamePasswordAuthenticationToken) {
                UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication;
//				((LinkedHashMap)authenticationToken.getPrincipal()).remove("username");
//				((LinkedHashMap)authenticationToken.getPrincipal()).remove("enabled");
//				((LinkedHashMap)authenticationToken.getPrincipal()).remove("accountNonExpired");
//				((LinkedHashMap)authenticationToken.getPrincipal()).remove("ignorable");
//				((LinkedHashMap)authenticationToken.getPrincipal()).remove("accountNonLocked");
//				((LinkedHashMap)authenticationToken.getPrincipal()).remove("credentialsNonExpired");

                String json = objectMapper.writeValueAsString(authenticationToken.getPrincipal()); //map转json
                LoginAppUser user = objectMapper.readValue(json, LoginAppUser.class);
                return user;
            } else if (authentication instanceof PreAuthenticatedAuthenticationToken) {
                // 刷新token方式
                PreAuthenticatedAuthenticationToken authenticationToken = (PreAuthenticatedAuthenticationToken) authentication;
                return (LoginAppUser) authenticationToken.getPrincipal();

            }
        }

        return null;
    }
}
